<template>
	<view class="order-content">
		<uv-sticky>
			<uv-tabs :list="statuses" @click="selectButton"
			lineWidth="30" 
					lineColor="#f56c6c" 
					:activeStyle="{
						color: '#303133',
						fontWeight: 'bold',
						transform: 'scale(1.05)'
			    	}"
					:inactiveStyle="{
						color: '#606266',
						transform: 'scale(1)'
					}" 
					itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;"></uv-tabs>
		</uv-sticky>
		<scroll-view scroll-y="true" @scrolltolower="onScroll" style="height: 100vh;" @scrolltoupper="onScrollTop">
			<view class="order-list">
				<uni-card v-if="list.length > 0" v-for="(item,index) in list" :key="index" padding="2"
	 margin="2"
	 :is-shadow="false">
					<view class="order">
						<view class="shop" @click="goShop(item)">
							<view class="shopname">
								<text>{{item.carts && item.carts.length > 0 ? item.carts[0].shopName : item.shopName}}</text>
								<uni-icons type="right" size="20" color="gray"></uni-icons>
							</view>
							<text v-if="item.orderStatus==0" class="status">
								待付款
							</text>
							<text v-if="item.orderStatus==1" class="status">
								已付款
							</text>
							<text v-if="item.orderStatus==2" class="status">
								待发货
							</text>
							<text v-if="item.orderStatus==3" class="status">
								卖家已发货
							</text>
							<text v-if="item.orderStatus==4" class="status">
								交易成功
							</text>
							<text v-if="item.orderStatus==5" class="status">
								已退款
							</text>
							<text v-if="item.orderStatus==6" class="status">
								已关闭
							</text>
						</view>
						<view v-if="item.carts" v-for="(order , orderindex) in item.carts" class="ordertail"  
						@click.stop="gotoOrderInfo(item.id)">
							<image mode="aspectFill"  :src="order.mainImage" style="border-radius: 5px;width: 50%;height: 100px;"></image>
							<view>
								<view style="display: flex;flex-direction: row;justify-content: space-between;">
									<view>
										<view style="color: black;font-weight: bold;">{{order.goodsName}}</view>
										<view style="padding: 0;margin: 0;" v-if="order.productSpecificationsDesc" 
										v-for="(spec,indexspec) in order.productSpecificationsDesc">{{spec}}</view>
									</view>
									<view class="price2">
										<el-text style="color: black;">¥ {{order.unitPrice}}</el-text>
										<el-text>x {{order.quantity}}</el-text>
									</view>
								</view>
								<view class="remark"  v-if="false">
									<text>退货包运费</text>
									<text>假一赔四</text>
								</view>
							</view>
						</view>
						<view v-else  class="ordertail" @click.stop="gotoOrderInfo(item.id)">
							<image  mode="aspectFill" :src="item.mainImage" style="border-radius: 5px;width: 50%;height: 100px;"></image>
							<view>
								<view style="display: flex;flex-direction: row;justify-content: space-between;">
									<view>
										<view style="color: black;font-weight: bold;">{{item.goodsName}}</view>
										<view style="padding: 0;margin: 0;"  v-if="item.productSpecificationsList" 
										v-for="(spec,indexspec) in item.productSpecificationsList">{{spec}}</view>
									</view>
									<view class="price2">
										<el-text style="color: black;">¥ {{item.placeOrderUnitPrice}}</el-text>
										<el-text>x {{item.placeOrderQuantity}}</el-text>
									</view>
								</view>
								<view class="remark" v-if="false">
									<text>退货包运费</text>
									<text>假一赔四</text>
								</view>
							</view>
						</view>
						<view class="price">
							<text>实付款:{{item.realTotalMoney}}</text>
						</view>
						<view class="btn">
							<!-- item.orderStatus!=6 -->
							<view  class="more" @click="morenBtn(item)"  v-if="false">
								<text>更多</text>
							</view>
							<view class="btn2" v-if="item.orderStatus==3">
								<button size="mini"  @click.stop="lookLogistics(item)">查看物流</button>
								<button size="mini" @click.stop="shouhuoBtn(item)" style="color: coral;background-color: #ffedd2;">确认收货</button>
							</view>
							<view class="btn2" v-if="item.orderStatus==4">
								<button size="mini" @click.stop="commentBtn(item)">评价</button>
								<button size="mini"  @click.stop="chartBtn(item)">加入购物车</button>
								<button size="mini" @click.stop="goToGoodDetail(item)" style="color: coral;background-color: #ffedd2;">再买一单</button>
							</view>
							<view class="btn2" v-if="item.orderStatus==0">
								<button size="mini" @click.stop="goToReceivingAddress()">修改地址</button>
								<button size="mini" @click.stop="payBtn(item)" style="color: coral;background-color: #ffedd2;">继续付款</button>
							</view>
							<view class="btn2" v-if="item.orderStatus==6">
								<button  size="mini" @click="deleteBtn(item)" style="padding-left: 6px;padding-right: 6px;">删除订单</button>
								<button  size="mini" @click="chartBtn(item)" style="padding-left: 6px;padding-right: 6px;">加入购物车</button>
								<button  size="mini" @click="goToGoodDetail(item)" style="padding-left: 6px;padding-right: 6px;">再买一单</button>
							</view>
						</view>
					</view>
				</uni-card>
				<uv-empty v-else text="请下单" mode="order"></uv-empty>
			</view>
		</scroll-view>
		<uv-modal ref="modalshouhuo" title="'确认收货'" content='是否确认收货?' @confirm="confirmShouHuo"></uv-modal>
		<uv-popup ref="popup2" @change="change2">
			<view>
				<uv-list>
				    <uv-list-item :clickable="true" @click="operBtn(item)"  v-for="(item,index) in menus"  border="true" direction="column" customStyle="color:gray;text-align:center;padding-top:10px;padding-bottom:10px;">
						{{item.text}}
					</uv-list-item>
				</uv-list>
			</view>
		</uv-popup>
		<uv-modal ref="modal" title="删除订单" content='是否删除该订单?' @confirm="confirm" show-cancel-button="true"></uv-modal>
		<uv-popup closeable="true" ref="popup" @change="change" mode="bottom" custom-style="border-top-left-radius: 5px;border-top-right-radius: 5px;">
			<view style="overflow:auto;height:80vh;">
				<view  class="commentcontent">
					<view v-for="(order,index) in orders" :key="index">
							<view class="xingxing">
								<view  class="comment-icon">
									<view style="display: flex;
					align-items: center;">
										<text style="margin-right: 5px;">描述相符</text>
										<uv-rate size="20" @change="changeDesc(order.goodsId,$event)"   gutter="15"  count="5" :value="0" activeColor="orange"></uv-rate>
									</view>
									<view  v-for="comment in commentList" v-if="commentList.length > 0 && hasProperty(commentList, 'orderId',order.id)">
										<text v-if="comment.descScore === 1">很差</text>
										<text v-if="comment.descScore === 2">一般</text>
										<text v-if="comment.descScore === 3">普通</text>
										<text v-if="comment.descScore === 4">很好</text>
										<text v-if="comment.descScore === 5">非常好</text>
									</view>
								</view>
								<view  class="comment-icon">
									<view style="display: flex;
					align-items: center;">
										<text style="margin-right: 5px;">服务态度</text>
										<uv-rate size="20" @change="changeService(order.goodsId,$event)"  gutter="15" count="5" :value="0" activeColor="orange"></uv-rate>
									</view>
									<view  v-for="comment in commentList" v-if="commentList.length > 0 && hasProperty(commentList, 'orderId',order.id)">
										<text v-if="comment.serviceScore === 1">很差</text>
										<text v-if="comment.serviceScore === 2">一般</text>
										<text v-if="comment.serviceScore === 3">普通</text>
										<text v-if="comment.serviceScore === 4">很好</text>
										<text v-if="comment.serviceScore === 5">非常好</text>
									</view>
								</view>
							</view>
							<view  @click.stop="clickImg(order.mainImage)" style="display: flex;flex-direction: row;
							padding: 10px;background-color: gainsboro;border-top: 1px solid lightgray;
							justify-content: center;
							">
								<image :src="order.mainImage" style="border-radius: 5px;width: 20px;height: 20px;margin-right: 5px;"></image>
								<view style="color: black;">{{order.goodsName}}</view>
							</view>
							<view class="inputcomment">
								<uv-textarea @input="changeInput($event,order.goodsId)" border="none" placeholder="请输入内容" height="100"></uv-textarea>
								<view v-for="comment in commentList" v-if="commentList.length > 0 && hasProperty(commentList, 'goodsId',order.goodsId)">
									<uv-upload v-if="comment.goodsId === order.goodsId"  :fileList="comment.fileList" name="3" multiple :maxCount="10" :previewFullImage="true"
									useBeforeRead="true"
									@afterRead="afterRead($event,order.goodsId)" 
											@delete="deletePic($event,order.goodsId)" customStyle="padding-left:5px;"></uv-upload>
								</view>
								<uv-upload v-else  :fileList="fileList2" name="3" multiple :maxCount="10" :previewFullImage="true"
								useBeforeRead="true"
								@afterRead="afterRead($event,order.goodsId)" 
										@delete="deletePic($event,order.goodsId)" customStyle="padding-left:5px;"></uv-upload>
							</view>
						</view>
				</view>
				<view class="publish">
					<uv-button text="发布" type="warning" @click="commentSubmit"></uv-button>
				</view>
			</view>
		</uv-popup>
		<loginDialog></loginDialog>
	</view>
</template>

<script lang="ts" setup>
import { ref, watchEffect } from 'vue'
import {getWxPayInfo, mypage,removeOrder, saveOrder,editOrder} from '@/api/order.ts'
import {saveComment} from '@/api/ordercomment.ts'
import { onLoad, onShow } from '@dcloudio/uni-app';
import {baseUrl} from '@/api/request.ts'
import {save} from '@/api/shoppingcart.ts'
import loginDialog from '@/pages/personcenter/login.vue'
const deleteBtn=(item)=>{
	currentOrderId.value=item.id
	modal.value.open()
}
const payBtn=(item)=>{
	// 仅作为示例，非真实参数信息。
	getWxPayInfo({"amount":item.placeOrderUnitPrice*item.placeOrderQuantity,"orderId":item.id}).then(res=>{
		// 仅作为示例，非真实参数信息。
		uni.requestPayment({
			provider: 'wxpay',
			timeStamp: res.data.timeStamp,
			nonceStr: res.data.nonceStr,
			package: res.data.packageVal,
			signType: res.data.signType,
			paySign:  res.data.paySign,
			success: function (res) {
				console.log('success:' + JSON.stringify(res));
				queryParams.value.page=1
				getList()
			},
			fail: function (err) {
				console.log('fail:' + JSON.stringify(err));
			}
		});
	})
}
const goToReceivingAddress=()=>{
  uni.navigateTo({
    url:'/pages/receivingaddress/index'
  })
}
const clickImg=(url)=> {
  wx.previewImage({
    urls: [url], //接受的是一个数组，默认展示第一张
    current: "",
    success: function (res) {},
    fail: function (res) {},
    complete: function (res) {},
  });
}
const changeService=(goodsId,e)=>{
	if(commentList.value.length > 0){
		let has=false;
		commentList.value.forEach(item=>{
			if(item.orderId === orderId.value && item.goodsId === goodsId){
				item.serviceScore=e;
				has=true;
			}
		})
		if(!has){
			commentList.value.push({
				goodsId:goodsId,
				orderId:orderId.value,
				serviceScore:e,
			});
		}
	}else{
		commentList.value.push({
			goodsId:goodsId,
			orderId:orderId.value,
			serviceScore:e,
		});
	}
}
const changeDesc=(goodsId,e)=>{
	if(commentList.value.length > 0){
		let has=false;
		commentList.value.forEach(item=>{
			if(item.orderId === orderId.value && item.goodsId === goodsId){
				item.descScore=e;
				has=true;
			}
		})
		if(!has){
			commentList.value.push({
				goodsId:goodsId,
				orderId:orderId.value,
				descScore:e,
			});
		}
	}else{
		commentList.value.push({
			goodsId:goodsId,
			orderId:orderId.value,
			descScore:e,
		});
	}
}
const hasProperty = (array, property, value) => {
  return array.some(item => item[property] === value);
};
const commentForm=ref({
	orderId:null,
	commentContent:null,
	commentPictures:null,
	serviceScore:null,
	descScore:null
})
//评论列表
const commentList=ref([])
const changeInput=(e,goodsId)=>{
	if(commentList.value.length > 0){
		let has=false;
		commentList.value.forEach(item=>{
			if(item.orderId === orderId.value && item.goodsId === goodsId){
				item.commentContent=e;
				has=true;
			}
		})
		if(!has){
			commentList.value.push({
				goodsId:goodsId,
				orderId:orderId.value,
				commentContent:e,
			});
		}
	}else{
		commentList.value.push({
			goodsId:goodsId,
			orderId:orderId.value,
			commentContent:e,
		});
	}
}
const commentSubmit=()=>{
	if(commentList.value.length == 0){
		uni.showToast({
			title:'评论不能为空'
		})
		return
	}
	commentList.value.forEach(item=>{
		if(!item.commentContent){
			uni.showToast({
				title:'评论内容不能为空'
			})
			return
		}
		if(!item.serviceScore){
			uni.showToast({
				title:'服务评分不能为空'
			})
			return
		}
		if(!item.descScore){
			uni.showToast({
				title:'描述评分不能为空'
			})
			return
		}
		saveComment(item).then(res=>{
			if(res.code == 200){
				uni.showToast({
					title:'评价成功'
				})
				popup.value.close()
			}
		})
	})
}
const onScroll =(e)=> {
	  console.log('滚动到底部了');
	  if(list.value.length < total.value && total.value > 0){
		  queryParams.value.page++;
		  getList()
	  }
}
const onScrollTop =(e)=> {
  console.log('滚动到顶部了');
  queryParams.value.page=1;
  getList()
}
const list=ref([])
const total = ref(0)
const queryParams=ref({
	page:1,
	limit:10,
	orderStatus:''
})
const getList=()=>{
	mypage(queryParams.value).then(res=>{
		if(queryParams.value.page ==1){
			list.value=res.data.list
		}else{
			list.value=list.value.concat(res.data.list) 
		}
		total.value=res.data.total
	})
}
onLoad(()=>{
	if(!uni.getStorageSync('token')){
		console.log("ho")
		uni.setStorageSync('login',true)
	}
	getList()
})
onShow(()=>{
	if(!uni.getStorageSync('token')){
		console.log("ho")
		uni.setStorageSync('login',true)
	}
	getList()
})
watchEffect(()=>{
	if(!uni.getStorageSync('token')){
		console.log("ho")
		uni.setStorageSync('login',true)
	}
	getList()
})
const modalshouhuo=ref(false) 
const confirmShouHuo=()=>{
	editOrder({"id":currentOrderId.value,"orderStatus":"4"}).then(res=>{
		if(res.code==200){
			uni.showToast({
				title:'确认收货成功'
			})
			queryParams.value.page=1;
			getList()
		}
	})
}
	
	const modal=ref(false)
	const confirm=()=> {
		let ids=[]
		ids.push(currentOrderId.value)
		removeOrder(ids).then(res=>{
			uni.showToast({
				title:'删除成功'
			})
			modal.value.close()
			popup2.value.close()
			queryParams.value.page=1
			getList()
		})
	}
	const operBtn=(item)=>{
		if(item.text==='删除订单'){
			modal.value.open()
		}else if(item.text==='查看物流'){
			uni.navigateTo({
				url:'/pages/order/logistics?id='+currentOrderId.value
			})
		}
	}
	const lookLogistics=(item)=>{
		uni.navigateTo({
			url:'/pages/order/logistics?id='+item.id
		})
	}
	const shouhuoBtn=(item)=>{
		currentOrderId.value=item.id
		modalshouhuo.value.open()
		queryParams.value.page=1;
		getList()
	}
	const menus=ref([
		{
			text:'删除订单'
		},
		{
			text:'查看物流'
		}
	])
	const popup2=ref()
	const currentOrderId=ref()
	const morenBtn=(val)=>{
		currentOrderId.value=val.id
		popup2.value.open('bottom');
		if(val.orderStatus=='0'){
			menus.value=[]
			/* [
				{
					text:'取消订单'
				},
				{
					text:'加入购物车'
				}
			] */
		}
	}
	const change2=()=>{
			
	}
	const currentIndex=ref(-1)
	const selectButton=(val)=>{
		// currentIndex.value=val
		console.log("val"+val.name)
		if(val.value){
			queryParams.value.orderStatus=val.value
		}else{
			queryParams.value.orderStatus=''
		}
		queryParams.value.page=1;
		getList()
	}
	const statuses=ref([
		{
			name:'全部',
			value:'',
		},
		{
			name:'待付款',
			value:'0',
		},
		{
			name:'待发货',
			value:'2',
		},
		{
			name:'待收货',
			value:'3',
		},
		{
			name:'退款/售后',
			value:'5',
		},
		{
			name:'待评价',
			value:'4',
		}
	])
	const fileList=ref([])
	const fileList2=ref([])
	const afterRead=async (e,goodsId)=>{
		let lists=[].concat(e.file)
		for (let i = 0; i < lists.length; i++) {
			await uploadFilePromise(lists[i].url,goodsId)
		}
	}
	const uploadFilePromise=(url,goodsId)=> {
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				url: baseUrl+'/app/common/upload', // 仅为示例，非真实的接口地址
				filePath: url,
				name: 'file',
				formData: {
					user: 'test'
				},
				success: (res) => {
					const urlimg=JSON.parse(res.data).data
					const url = baseUrl+urlimg;
					
					if(commentList.value.length > 0){
						let has=false;
						commentList.value.forEach(item=>{
							if(item.orderId === orderId.value && goodsId===item.goodsId){
								if(item.commentPictures){
									item.commentPictures=item.commentPictures.concat(","+urlimg)
								}else{
									item.commentPictures=urlimg
								}
								if(item.fileList){
									console.log("11")
									item.fileList.push({url:url})
								}else{
									item.fileList=[]
									item.fileList.push({url:url})
								}
								has=true;
							}
						})
						if(!has){
							console.log("222")
							let fileList=[]
							fileList.push({url:url})
							commentList.value.push({
								goodsId:goodsId,
								fileList:fileList,
								orderId:orderId.value,
								commentPictures:urlimg,
							});
						}
					}else{
						fileList.value.push({url:url})
						commentList.value.push({
							fileList:fileList.value,
							orderId:orderId.value,
							goodsId:goodsId,
							commentPictures:urlimg,
						});
					}
				}
			});
		})
	}
	const deletePic=(e,goodsId)=>{
		const url = e.file.url.substring(e.file.url.indexOf('/profile'))
		commentList.value.forEach(item=>{
			if(item.orderId === orderId.value && goodsId===item.goodsId){
				let pics=item.commentPictures.split(',')
				const index = pics.indexOf(url);
				if (index !== -1) {
					pics.splice(index, 1);
					item.commentPictures=pics.join(",")
				}
				item.fileList.forEach(it=>{
					const index = item.fileList.findIndex(it => it.url ===  e.file.url);
					if(index != -1){
						item.fileList.splice(index, 1);
					}					
				})
			}
		})
	}
	const value=ref(2)
	const orders=ref([])
	const orderId=ref()
	const commentBtn=(val)=>{
		orderId.value=val.id
		if(val.carts){
			orders.value=val.carts;
		}else{
			orders.value.push(val);
		}
		commentList.value=[]
		fileList2.value=[]
		fileList.value=[]
		popup.value.open()
	}
	const popup=ref(false)
	const change=(e)=>{
		console.log('弹窗状态改变：',e);
	}
	const gotoOrderInfo=(val)=>{
		uni.navigateTo({
		  url:'/pages/order/detail?id='+val,
		})
	}
	const goShop=(item)=>{
		const shopId=item.carts && item.carts.length > 0 ?item.carts[0].shopId:item.shopId
		uni.navigateTo({
			url:"/pages/shop/index?id="+shopId
		})
	}
	const chartBtn=(order)=>{
		if(order.carts){
			order.carts.forEach(item=>{
				const cartForm=ref({
					"goodsId":item.goodsId,
					"quantity":item.quantity,
					"productSpecificationsIds":item.productSpecificationsIds,
					"totalPrice":item.totalPrice,
					"unitPrice":item.unitPrice})
				save(cartForm.value).then(res=>{
					if(res.code == 200){
						uni.switchTab({
							 url:'/pages/chart/index'
						})
					}
				})
			})
		}else{
			const cartForm=ref({
				"goodsId":order.goodsId,
				"quantity":order.placeOrderQuantity,
				"productSpecificationsIds":order.productSpecificationsIds,
				"totalPrice":order.placeOrderQuantity*order.placeOrderUnitPrice,
				"unitPrice":order.placeOrderUnitPrice})
			save(cartForm.value).then(res=>{
				if(res.code == 200){
					uni.switchTab({
						 url:'/pages/chart/index'
					})
				}
			})
		}
		
	}
	const goToGoodDetail=(item)=>{
		if(item.carts){
			if(item.carts.length > 1){
				uni.navigateTo({
					url:"/pages/shop/index?id="+item.shopId
				})
			}else{
				uni.navigateTo({
					url:"/pages/goods/detail?id="+item.carts[0].goodsId
				})
			}
		}else{
			uni.navigateTo({
				url:"/pages/goods/detail?id="+item.goodsId
			})
		}
	}
</script>
<style scoped>	
	.order-list{
		height: 100vh;
		overflow: auto;
		width: 100%;
		margin-top: 10px;
	}
	.order-content{
		height: 100%;
		width: 100%;
	}
	.status-order{
		/* display: flex;
		align-items: center;
		justify-content: space-evenly;
		width: 100%; */
		position: absolute;
		top:0;
		/* background-color: whitesmoke;
		padding-top: 10px;
		padding-bottom: 10px; */
	}
	.upload{
		position: absolute;
		bottom: 0;
		left: 0;
	}
	.inputcomment{
		position: relative;
	}
	.xingxing{
		padding: 5px;
		background-color: #dedede;
	}
	.comment-icon{
		display: flex;
		align-items: center;
		justify-content: space-around;
		font-size: 14px;
		color: gray;
	}
.price2{
	display: flex;
	flex-direction: column;
	text-align: right;
	width: 30%;
}	
.remark{
	width: 100%;
	display: flex;
	justify-content: space-between;
	color: coral;
}	
.order view{
	margin-bottom: 8px;
	margin-left: 5px;
}
.btn{
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
}
.more{
	width:15%;
	display: flex;
	flex-direction: column;
}
.btn2{
	width: 100%;
	text-align: right;
}
.btn2 button{
	padding-left: 6px;
	padding-right: 6px;
	margin-right: 10px;
}
.price{
	text-align: right;
	color: black;
}
.ordertail{
	display: flex;
	justify-content: space-between;
	width:100%;
}
.shop{
	display: flex;justify-content: space-between;
	align-items: center;
}
.shopname{
	display: flex;align-items: center;justify-content: space-evenly;
	color: black;
}
.status{
	color: coral;
}
.commentcontent{
	overflow: auto;
	height: 90%;
	width: 100%;
}
</style>